package com.surelution.projects.crm
import groovy.time.TimeCategory
import java.text.SimpleDateFormat

class GasPlanListController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
		def sdf = new SimpleDateFormat('yyyy-MM-dd')
		def dateFrom = params.dateFrom? params.dateFrom:null
		def dateTo = params.dateTo? params.dateTo:null
		def stationCode = params['station.id']?OwnStation.get(params['station.id']).code.toString():null
		def result = GasPlanList.createCriteria().list ([max:params.max, offset:params.offset]){
			if(stationCode){
				eq("stationCode",stationCode)
			}
			if(dateFrom) {
				ge("planTime", dateFrom)
			}
			if(dateTo) {
				le("planTime", dateTo)
			}
		}
        [gasPlanListInstanceList: result, gasPlanListInstanceTotal: result.totalCount]
    }
	
	def ImportExcelService
	def springSecurityService
	def gasPlanImport = {
		int fromLine = 0
		def file = params.gasPlanList
		int lineNum = 0
		def fileName = file.originalFilename
		ImportExcel excel = ImportExcelService.storeFile(file.inputStream,fileName)
		BufferedReader reader = new BufferedReader(new InputStreamReader(file.inputStream, "utf-16"))

			reader.eachLine {line->
			if(lineNum > fromLine) {
				String[] words = line.split()
				println words
				if(words.length > 18) {
					GasPlanList gasPlanList = GasPlanList.createCriteria().get {
						eq("stationCode", words[0])
						eq("planTime", words[3])
					}					
					if(!gasPlanList){
						gasPlanList = new GasPlanList(
						stationCode:"${words[0]}",stationProperty:"${words[1]}",yearlyMonthly:"${words[2]}",planTime:"${words[3]}",
						unitName:"${words[16]}",createTime:"${words[17]}",username:"${words[18]}",
						)
					}
					gasPlanList.gasolineAmount = words[4].toString()
					gasPlanList.fuelAmount = words[5].replaceAll('"','').replaceAll(',','')
					gasPlanList.retailAmount = words[6].toString().replaceAll(',','')
					gasPlanList.selfRetailGasAmount = words[7].replaceAll(',','')
					gasPlanList.selfRetailFuelAmount = words[8].replaceAll(',','')
					gasPlanList.selfRetailAmount = words[9].replaceAll(',','')
					gasPlanList.pureGunRetailGas = words[10].replaceAll(',','')
					gasPlanList.pureGunRetailFuel = words[11].replaceAll(',','')
					gasPlanList.pureGunRetailAmount = words[12].replaceAll(',','')
					gasPlanList.smallSendGas = words[13].replaceAll(',','')
					gasPlanList.smallSendFuel = words[14].replaceAll(',','')
					gasPlanList.smallSendAmount = words[15].replaceAll(',','')
					gasPlanList.directionDeclare = "none"
					gasPlanList.countYear = "none"
					gasPlanList.save()
					println gasPlanList
					
					int gasoline = Integer.parseInt(words[4].replaceAll(',','').replaceAll('"',''))
					int fuel = Integer.parseInt(words[5].replaceAll(',','').replaceAll('"',''))
					int retail = Integer.parseInt(words[6].replaceAll(',','').replaceAll('"',''))
					def station = OwnStation.findByCode(words[0])
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM")
					SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy")
					Date planTime = new Date()
					
					if(words[2] =='M'){
						planTime = sdf.parse(words[3])
						GasPlanSum gasPlanSum = GasPlanSum.createCriteria().get {
							eq("station", station)
							eq("planTime", planTime)
						}
						if (!gasPlanSum){
							gasPlanSum = new GasPlanSum(planTime:"${planTime}")
						}
						gasPlanSum.gasolineAmount = gasoline
						gasPlanSum.fuelAmount = fuel 
						gasPlanSum.retailAmount = retail
						gasPlanSum.station = OwnStation.findByCode(words[0])
						gasPlanSum.save()
						println gasPlanSum
					}
					else{
						planTime = sdf1.parse(words[3])
						GasPlanYearSum gasPlanYearSum = GasPlanYearSum.createCriteria().get {
							eq("station", station)
							eq("planTime", planTime)
						}
						if (!gasPlanYearSum){
							planTime = sdf1.parse(words[3])
							gasPlanYearSum = new GasPlanYearSum(planTime:"${planTime}")
						}
						gasPlanYearSum.gasolineAmount = gasoline
						gasPlanYearSum.fuelAmount = fuel
						gasPlanYearSum.retailAmount = retail
						gasPlanYearSum.station = OwnStation.findByCode(words[0])
						gasPlanYearSum.save()
						println gasPlanYearSum
					}
				}
			}
			lineNum++
		}
		excel.uploader = springSecurityService.principal.username
		excel.type = "油品销售计划"
		excel.save()
		flash.message = "${message(code: 'default.updateFileSuccess.message', args: [message(code: 'gasPlanList.label', default: 'gasPlanList')])}"
		redirect(action:"list" ,controller:"gasPlanList")
	}
	
	
    def create = {
        def gasPlanListInstance = new GasPlanList()
        gasPlanListInstance.properties = params
        return [gasPlanListInstance: gasPlanListInstance]
    }

    def save = {
        def gasPlanListInstance = new GasPlanList(params)
        if (gasPlanListInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'gasPlanList.label', default: 'GasPlanList'), gasPlanListInstance.id])}"
            redirect(action: "show", id: gasPlanListInstance.id)
        }
        else {
            render(view: "create", model: [gasPlanListInstance: gasPlanListInstance])
        }
    }

    def show = {
        def gasPlanListInstance = GasPlanList.get(params.id)
        if (!gasPlanListInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'gasPlanList.label', default: 'GasPlanList'), params.id])}"
            redirect(action: "list")
        }
        else {
            [gasPlanListInstance: gasPlanListInstance]
        }
    }

    def edit = {
        def gasPlanListInstance = GasPlanList.get(params.id)
        if (!gasPlanListInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'gasPlanList.label', default: 'GasPlanList'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [gasPlanListInstance: gasPlanListInstance]
        }
    }

    def update = {
        def gasPlanListInstance = GasPlanList.get(params.id)
        if (gasPlanListInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (gasPlanListInstance.version > version) {
                    
                    gasPlanListInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'gasPlanList.label', default: 'GasPlanList')] as Object[], "Another user has updated this GasPlanList while you were editing")
                    render(view: "edit", model: [gasPlanListInstance: gasPlanListInstance])
                    return
                }
            }
            gasPlanListInstance.properties = params
            if (!gasPlanListInstance.hasErrors() && gasPlanListInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'gasPlanList.label', default: 'GasPlanList'), gasPlanListInstance.id])}"
                redirect(action: "show", id: gasPlanListInstance.id)
            }
            else {
                render(view: "edit", model: [gasPlanListInstance: gasPlanListInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'gasPlanList.label', default: 'GasPlanList'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def gasPlanListInstance = GasPlanList.get(params.id)
        if (gasPlanListInstance) {
            try {
                gasPlanListInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'gasPlanList.label', default: 'GasPlanList'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'gasPlanList.label', default: 'GasPlanList'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'gasPlanList.label', default: 'GasPlanList'), params.id])}"
            redirect(action: "list")
        }
    }
}
